package com.cxyd.modules.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cxyd.common.page.PageData;
import com.cxyd.common.service.impl.CrudServiceImpl;
import com.cxyd.common.utils.ConvertUtils;
import com.cxyd.modules.sys.dto.SysUserDTO;
import com.cxyd.modules.sys.service.SysUserService;
import com.cxyd.modules.wms.dao.SupplierDao;
import com.cxyd.modules.wms.dto.SupplierDTO;
import com.cxyd.modules.wms.entity.SupplierEntity;
import com.cxyd.modules.wms.service.SupplierService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 厂家信息
 *
 * @author g_Cycle gengruyi01@163.com
 * @since 1.0.0 2023-04-27
 */
@Service
public class SupplierServiceImpl extends CrudServiceImpl<SupplierDao, SupplierEntity, SupplierDTO> implements SupplierService {
    private final SysUserService userService;

    public SupplierServiceImpl(SysUserService userService) {
        this.userService = userService;
    }

    @Override
    public PageData<SupplierDTO> page(Map<String, Object> params) {
        //1.查询物料信息
        final IPage<SupplierEntity> page = baseDao.selectPage(
                getPage(params, "id", true),
                getWrapper(params)
        );
        //2.获取用户信息
        final List<SysUserDTO> userList = userService.getList();
        //3.将creator与updater的username通过id进行绑定
        page.getRecords().forEach(entity -> {
            if (entity.getCreator() != null) {
                entity.setCreatorName(userService.getUsernameById(entity.getCreator(), userList));
            }
            if (entity.getUpdater() != null) {
                entity.setUpdaterName(userService.getUsernameById(entity.getUpdater(), userList));
            }
        });
        return getPageData(page, SupplierDTO.class);
    }

    @Override
    public QueryWrapper<SupplierEntity> getWrapper(Map<String, Object> params) {
        //查询条件
        String supplierCode = (String) params.get("supplierCode");
        String SupplierName = (String) params.get("supplierName");

        QueryWrapper<SupplierEntity> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(supplierCode), "supplier_code", supplierCode);
        wrapper.like(StringUtils.isNotBlank(SupplierName), "supplier_name", SupplierName);
        return wrapper;
    }

    @Override
    public SupplierDTO getSupplierByCode(String supplierCode) {
        QueryWrapper<SupplierEntity> qw = new QueryWrapper<SupplierEntity>().eq("supplier_code", supplierCode).last("LIMIT 1");
        SupplierEntity entity = baseDao.selectOne(qw);
        return ConvertUtils.sourceToTarget(entity, SupplierDTO.class);
    }
}